import React, { useRef } from 'react'
import { connect } from 'react-redux'
import { actions } from '../../store/reducers/count'

function Count(props) {
  const { count, increment, decrement, incrementAsync } = props
  const selectNumberRef = useRef()

  // 加
  const onIncrement = () => {
    const { value } = selectNumberRef.current
    increment(+value)
  }

  // 减
  const onDecrement = () => {
    const { value } = selectNumberRef.current
    decrement(+value)
  }

  // 如果为奇数，则加
  const onIncrementIfOdd = () => {
    const { value } = selectNumberRef.current
    if (count % 2 !== 0) {
      increment(+value)
    }
  }

  // 异步延迟加
  const onIncrementIfAsync = () => {
    const { value } = selectNumberRef.current
    incrementAsync(+value, 500)
  }

  return (
    <div>
      <h1>当前求和为：{count}</h1>
      <select ref={selectNumberRef}>
        <option value='1'>1</option>
        <option value='2'>2</option>
        <option value='3'>3</option>
      </select>
      <button onClick={onIncrement}>+</button>
      <button onClick={onDecrement}>-</button>
      <button onClick={onIncrementIfOdd}>当前求和为奇数再加</button>
      <button onClick={onIncrementIfAsync}>异步加</button>
    </div>
  )
}

export default connect(({ count }) => ({ count }), {
  increment: actions.increment,
  decrement: actions.decrement,
  incrementAsync: actions.incrementAsync
})(Count)
